<template>
  <div class="algorithm-management">
    <div class="management-header">
      <h3>AI算法管理</h3>
      <div class="header-actions">
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
        <el-button type="success" @click="startAllServices">启动所有服务</el-button>
        <el-button type="danger" @click="stopAllServices">停止所有服务</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="algorithm-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ totalAlgorithms }}</div>
            <div class="stat-label">总算法数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card running">
            <div class="stat-number">{{ runningAlgorithms }}</div>
            <div class="stat-label">运行中</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card inactive">
            <div class="stat-number">{{ inactiveAlgorithms }}</div>
            <div class="stat-label">已停止</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card accuracy">
            <div class="stat-number">88.5%</div>
            <div class="stat-label">平均准确率</div>
          </div>
        </el-col>
      </el-row>
    </div>



    <!-- 按服务分组的算法管理 -->
    <div class="services-management">
      <el-tabs v-model="activeServiceTab" type="border-card">
        <el-tab-pane 
          v-for="(serviceInfo, serviceId) in AI_SERVICES_WITH_ALGORITHMS" 
          :key="serviceId"
          :label="serviceInfo.name" 
          :name="serviceId"
        >
          <div class="service-content">
            <!-- 服务描述 -->
            <div class="service-description">
              <h4>{{ serviceInfo.name }}</h4>
              <p>{{ getServiceDescription(serviceId) }}</p>
              <div class="service-stats">
                <el-tag type="success">运行中: {{ getServiceRunningCount(serviceId) }}</el-tag>
                <el-tag type="info">总计: {{ Object.keys(serviceInfo.algorithms).length }}</el-tag>
                <el-tag type="warning">准确率: {{ getServiceAccuracy(serviceId) }}%</el-tag>
              </div>
            </div>
            
            <!-- 服务操作 -->
            <div class="service-actions">
              <el-button 
                type="success" 
                size="small" 
                @click="startService(serviceId)"
                :loading="serviceLoading[serviceId]"
              >
                启动服务
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="stopService(serviceId)"
                :loading="serviceLoading[serviceId]"
              >
                停止服务
              </el-button>
            </div>
            
            <!-- 算法网格 -->
            <div class="algorithms-grid">
              <div 
                v-for="(algorithmName, algorithmType) in serviceInfo.algorithms"
                :key="algorithmType"
                class="algorithm-card"
                :class="{ 
                  'running': isAlgorithmRunning(serviceId, algorithmType),
                  'inactive': !isAlgorithmRunning(serviceId, algorithmType)
                }"
              >
                <div class="algorithm-header">
                  <div class="algorithm-title">
                    <h5>{{ algorithmName }}</h5>
                    <el-tag 
                      :type="isAlgorithmRunning(serviceId, algorithmType) ? 'success' : 'info'"
                      size="small"
                    >
                      {{ isAlgorithmRunning(serviceId, algorithmType) ? '运行中' : '已停止' }}
                    </el-tag>
                  </div>
                  <div class="algorithm-actions">
                    <el-button 
                      v-if="!isAlgorithmRunning(serviceId, algorithmType)"
                      type="success" 
                      size="small" 
                      @click="startAlgorithm(serviceId, algorithmType)"
                      :loading="algorithmLoading[`${serviceId}_${algorithmType}`]"
                    >
                      启动
                    </el-button>
                    <el-button 
                      v-else
                      type="danger" 
                      size="small" 
                      @click="stopAlgorithm(serviceId, algorithmType)"
                      :loading="algorithmLoading[`${serviceId}_${algorithmType}`]"
                    >
                      停止
                    </el-button>
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="configureAlgorithm(serviceId, algorithmType)"
                    >
                      配置
                    </el-button>
                  </div>
                </div>
                
                <div class="algorithm-info">
                  <p class="algorithm-id">ID: {{ algorithmType }}</p>
                  <p class="algorithm-desc">{{ getAlgorithmDescription(serviceId, algorithmType) }}</p>
                </div>
                
                <!-- 算法性能指标 -->
                <div class="algorithm-metrics" v-if="isAlgorithmRunning(serviceId, algorithmType)">
                  <el-divider />
                  <div class="metrics-grid">
                    <div class="metric">
                      <span class="metric-label">准确率</span>
                      <span class="metric-value">{{ getAlgorithmAccuracy(serviceId, algorithmType) }}%</span>
                    </div>
                    <div class="metric">
                      <span class="metric-label">处理帧数</span>
                      <span class="metric-value">{{ getAlgorithmFrames(serviceId, algorithmType) }}</span>
                    </div>
                    <div class="metric">
                      <span class="metric-label">响应时间</span>
                      <span class="metric-value">{{ getAlgorithmResponseTime(serviceId, algorithmType) }}ms</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 算法配置对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      :title="`配置算法: ${currentAlgorithm?.name}`"
      width="600px"
    >
      <el-form :model="algorithmConfig" label-width="120px">
        <el-form-item label="置信度阈值">
          <el-slider 
            v-model="algorithmConfig.confidence_threshold" 
            :min="0.1" 
            :max="1" 
            :step="0.1"
            show-input
          />
        </el-form-item>
        <el-form-item label="检测间隔(秒)">
          <el-input-number 
            v-model="algorithmConfig.detection_interval" 
            :min="1" 
            :max="60"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最大检测数">
          <el-input-number 
            v-model="algorithmConfig.max_detections" 
            :min="1" 
            :max="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="启用算法">
          <el-switch v-model="algorithmConfig.enabled" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAlgorithmConfig">保存配置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { aiAlgorithmApi } from '@/api/ai-algorithm'

// 六大AI服务及其具体算法
const AI_SERVICES_WITH_ALGORITHMS = {
  'campus_behavior_monitoring': {
    'name': '校园行为监控',
    'algorithms': {
      'person_detection': '人员检测算法',
      'behavior_analysis': '行为分析算法',
      'abnormal_behavior': '异常行为识别',
      'crowd_gathering': '人群聚集检测',
      'violence_detection': '暴力行为检测'
    }
  },
  'campus_crowd_safety': {
    'name': '校园人群安全',
    'algorithms': {
      'crowd_density': '人群密度分析',
      'crowd_flow': '人流量统计',
      'evacuation_route': '疏散路径规划',
      'safety_monitoring': '安全监控算法',
      'emergency_detection': '紧急情况检测'
    }
  },
  'campus_energy_management': {
    'name': '校园能源管理',
    'algorithms': {
      'lighting_control': '照明控制算法',
      'occupancy_detection': '空间占用检测',
      'energy_optimization': '能耗优化算法',
      'equipment_monitoring': '设备监控算法',
      'power_analysis': '电力分析算法'
    }
  },
  'campus_environment_hygiene': {
    'name': '校园环境卫生',
    'algorithms': {
      'waste_detection': '垃圾检测算法',
      'cleanliness_assessment': '清洁度评估',
      'hygiene_monitoring': '卫生监控算法',
      'cleaning_efficiency': '清洁效率分析',
      'maintenance_alert': '维护提醒算法'
    }
  },
  'intelligent_classroom_quality': {
    'name': '智能课堂质量',
    'algorithms': {
      'attention_analysis': '注意力分析',
      'participation_tracking': '参与度跟踪',
      'learning_assessment': '学习效果评估',
      'classroom_environment': '课堂环境监测',
      'interaction_analysis': '互动分析算法'
    }
  },
  'teaching_quality_assessment': {
    'name': '教学质量评估',
    'algorithms': {
      'teacher_behavior': '教师行为分析',
      'teaching_style': '教学风格识别',
      'student_engagement': '学生参与度分析',
      'content_delivery': '内容传达效果',
      'feedback_analysis': '反馈分析算法'
    }
  }
}

// 响应式数据
const algorithms = ref([])
const loading = ref(false)
const activeServiceTab = ref('campus_behavior_monitoring')
const serviceLoading = reactive({})
const algorithmLoading = reactive({})
const showConfigDialog = ref(false)
const currentAlgorithm = ref(null)
const algorithmConfig = reactive({
  confidence_threshold: 0.7,
  detection_interval: 5,
  max_detections: 10,
  enabled: true
})

// 计算属性
const totalAlgorithms = computed(() => {
  return algorithms.value.length
})

const runningAlgorithms = computed(() => {
  return algorithms.value.filter(alg => alg.status === 'running').length
})

const inactiveAlgorithms = computed(() => {
  return algorithms.value.filter(alg => alg.status === 'inactive').length
})

// 工具方法
const getServiceDescription = (serviceId) => {
  const descriptions = {
    'campus_behavior_monitoring': '智能识别和分析校园内人员行为，确保校园安全',
    'campus_crowd_safety': '监控人群密度和流动，预防安全事故发生',
    'campus_energy_management': '优化校园能源使用，实现绿色智能管理',
    'campus_environment_hygiene': '监测校园环境质量，维护清洁卫生标准',
    'intelligent_classroom_quality': '分析课堂教学质量，提升教育效果',
    'teaching_quality_assessment': '评估教师教学水平，优化教学方法'
  }
  return descriptions[serviceId] || '智能AI服务'
}

const getAlgorithmDescription = (serviceId, algorithmType) => {
  const descriptions = {
    'campus_behavior_monitoring': {
      'person_detection': '检测和识别校园内的人员',
      'behavior_analysis': '分析人员行为模式',
      'abnormal_behavior': '识别异常或可疑行为',
      'crowd_gathering': '检测人群聚集情况',
      'violence_detection': '检测暴力行为'
    },
    'campus_crowd_safety': {
      'crowd_density': '分析区域人群密度',
      'crowd_flow': '统计人流量和方向',
      'evacuation_route': '规划最优疏散路径',
      'safety_monitoring': '实时安全监控',
      'emergency_detection': '检测紧急情况'
    },
    'campus_energy_management': {
      'lighting_control': '智能照明控制',
      'occupancy_detection': '检测空间占用情况',
      'energy_optimization': '优化能源使用',
      'equipment_monitoring': '监控设备运行状态',
      'power_analysis': '分析电力使用情况'
    },
    'campus_environment_hygiene': {
      'waste_detection': '检测垃圾和废物',
      'cleanliness_assessment': '评估清洁度',
      'hygiene_monitoring': '监控卫生状况',
      'cleaning_efficiency': '分析清洁效率',
      'maintenance_alert': '维护提醒'
    },
    'intelligent_classroom_quality': {
      'attention_analysis': '分析学生注意力',
      'participation_tracking': '跟踪学生参与度',
      'learning_assessment': '评估学习效果',
      'classroom_environment': '监测课堂环境',
      'interaction_analysis': '分析师生互动'
    },
    'teaching_quality_assessment': {
      'teacher_behavior': '分析教师行为',
      'teaching_style': '识别教学风格',
      'student_engagement': '分析学生参与度',
      'content_delivery': '评估内容传达效果',
      'feedback_analysis': '分析反馈信息'
    }
  }
  return descriptions[serviceId]?.[algorithmType] || '专业AI算法'
}

const isAlgorithmRunning = (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
  return algorithm?.status === 'running'
}

const getServiceRunningCount = (serviceId) => {
  const serviceAlgorithms = Object.keys(AI_SERVICES_WITH_ALGORITHMS[serviceId].algorithms)
  return serviceAlgorithms.filter(algorithmType => 
    isAlgorithmRunning(serviceId, algorithmType)
  ).length
}

const getServiceAccuracy = (serviceId) => {
  return 85 + (Math.abs(serviceId.split('').reduce((a, b) => a + b.charCodeAt(0), 0)) % 15)
}

const getAlgorithmAccuracy = (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
  return algorithm?.accuracy || 85
}

const getAlgorithmFrames = (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
  return algorithm?.processedFrames || 0
}

const getAlgorithmResponseTime = (serviceId, algorithmType) => {
  return Math.floor(Math.random() * 50) + 10
}

// 数据加载
const loadAlgorithms = async () => {
  loading.value = true
  try {
    const response = await aiAlgorithmApi.getAlgorithmList({
      page: 1,
      size: 50
    })
    
    if (response.code === 200) {
      algorithms.value = response.rows || []
      console.log('✅ 算法数据加载成功:', algorithms.value.length, '个算法')
    } else {
      throw new Error(response.msg || '获取算法列表失败')
    }
  } catch (error) {
    console.error('❌ 获取算法列表失败:', error)
    ElMessage.error('获取算法列表失败')
    // 生成模拟数据
    generateMockAlgorithms()
  } finally {
    loading.value = false
  }
}

const generateMockAlgorithms = () => {
  const mockAlgorithms = []
  
  Object.entries(AI_SERVICES_WITH_ALGORITHMS).forEach(([serviceId, serviceInfo]) => {
    Object.entries(serviceInfo.algorithms).forEach(([algorithmType, algorithmName]) => {
      const algorithmId = `${serviceId}_${algorithmType}`
      mockAlgorithms.push({
        id: algorithmId,
        name: algorithmName,
        type: serviceId,
        service_name: serviceInfo.name,
        algorithm_type: algorithmType,
        status: Math.random() > 0.5 ? 'running' : 'inactive',
        accuracy: 80 + Math.floor(Math.random() * 20),
        processedFrames: Math.floor(Math.random() * 10000) + 1000,
        version: '1.0.0',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      })
    })
  })
  
  algorithms.value = mockAlgorithms
  console.log('✅ 生成模拟算法数据:', mockAlgorithms.length, '个算法')
}

// 算法操作
const startAlgorithm = async (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  algorithmLoading[algorithmId] = true
  
  try {
    const response = await aiAlgorithmApi.startAlgorithm(algorithmId)
    if (response.code === 200) {
      ElMessage.success('算法启动成功')
      // 更新本地状态
      const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
      if (algorithm) {
        algorithm.status = 'running'
      }
    } else {
      throw new Error(response.msg || '启动失败')
    }
  } catch (error) {
    console.error('启动算法失败:', error)
    ElMessage.error('启动算法失败')
  } finally {
    algorithmLoading[algorithmId] = false
  }
}

const stopAlgorithm = async (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  algorithmLoading[algorithmId] = true
  
  try {
    const response = await aiAlgorithmApi.stopAlgorithm(algorithmId)
    if (response.code === 200) {
      ElMessage.success('算法停止成功')
      // 更新本地状态
      const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
      if (algorithm) {
        algorithm.status = 'inactive'
      }
    } else {
      throw new Error(response.msg || '停止失败')
    }
  } catch (error) {
    console.error('停止算法失败:', error)
    ElMessage.error('停止算法失败')
  } finally {
    algorithmLoading[algorithmId] = false
  }
}

const startService = async (serviceId) => {
  serviceLoading[serviceId] = true
  
  try {
    const response = await aiAlgorithmApi.startAlgorithm(serviceId)
    if (response.code === 200) {
      ElMessage.success('服务启动成功')
      // 更新所有该服务下的算法状态
      Object.keys(AI_SERVICES_WITH_ALGORITHMS[serviceId].algorithms).forEach(algorithmType => {
        const algorithmId = `${serviceId}_${algorithmType}`
        const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
        if (algorithm) {
          algorithm.status = 'running'
        }
      })
    } else {
      throw new Error(response.msg || '启动失败')
    }
  } catch (error) {
    console.error('启动服务失败:', error)
    ElMessage.error('启动服务失败')
  } finally {
    serviceLoading[serviceId] = false
  }
}

const stopService = async (serviceId) => {
  serviceLoading[serviceId] = true
  
  try {
    const response = await aiAlgorithmApi.stopAlgorithm(serviceId)
    if (response.code === 200) {
      ElMessage.success('服务停止成功')
      // 更新所有该服务下的算法状态
      Object.keys(AI_SERVICES_WITH_ALGORITHMS[serviceId].algorithms).forEach(algorithmType => {
        const algorithmId = `${serviceId}_${algorithmType}`
        const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
        if (algorithm) {
          algorithm.status = 'inactive'
        }
      })
    } else {
      throw new Error(response.msg || '停止失败')
    }
  } catch (error) {
    console.error('停止服务失败:', error)
    ElMessage.error('停止服务失败')
  } finally {
    serviceLoading[serviceId] = false
  }
}

const startAllServices = async () => {
  try {
    await ElMessageBox.confirm('确定要启动所有AI服务吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    for (const serviceId of Object.keys(AI_SERVICES_WITH_ALGORITHMS)) {
      await startService(serviceId)
    }
    
    ElMessage.success('所有服务启动成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启动所有服务失败:', error)
    }
  }
}

const stopAllServices = async () => {
  try {
    await ElMessageBox.confirm('确定要停止所有AI服务吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    for (const serviceId of Object.keys(AI_SERVICES_WITH_ALGORITHMS)) {
      await stopService(serviceId)
    }
    
    ElMessage.success('所有服务停止成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('停止所有服务失败:', error)
    }
  }
}

const configureAlgorithm = (serviceId, algorithmType) => {
  const algorithmId = `${serviceId}_${algorithmType}`
  const algorithm = algorithms.value.find(alg => alg.id === algorithmId)
  
  if (algorithm) {
    currentAlgorithm.value = {
      id: algorithmId,
      name: algorithm.name,
      serviceId,
      algorithmType
    }
    
    // 设置当前配置
    algorithmConfig.confidence_threshold = algorithm.config?.confidence_threshold || 0.7
    algorithmConfig.detection_interval = algorithm.config?.detection_interval || 5
    algorithmConfig.max_detections = algorithm.config?.max_detections || 10
    algorithmConfig.enabled = algorithm.status === 'running'
    
    showConfigDialog.value = true
  }
}

const saveAlgorithmConfig = () => {
  console.log('保存算法配置:', currentAlgorithm.value, algorithmConfig)
  ElMessage.success('算法配置保存成功')
  showConfigDialog.value = false
}

const refreshData = () => {
  loadAlgorithms()
}

// 生命周期
onMounted(() => {
  console.log('=== AI算法管理组件初始化 ===')
  loadAlgorithms()
})
</script>

<style lang="scss" scoped>
.algorithm-management {
  padding: 20px;
  
  .management-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      margin: 0;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .algorithm-stats {
    margin-bottom: 20px;
    
    .stat-card {
      background: white;
      border-radius: 8px;
      padding: 20px;
      text-align: center;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-left: 4px solid #409eff;
      
      &.running {
        border-left-color: #67c23a;
      }
      
      &.inactive {
        border-left-color: #909399;
      }
      
      &.accuracy {
        border-left-color: #e6a23c;
      }
      
      .stat-number {
        font-size: 28px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #606266;
      }
    }
  }
  

  
  .services-management {
    .service-content {
      .service-description {
        background: #f8f9fa;
        padding: 16px;
        border-radius: 8px;
        margin-bottom: 20px;
        
        h4 {
          margin: 0 0 8px 0;
          color: #303133;
        }
        
        p {
          margin: 0 0 12px 0;
          color: #606266;
          line-height: 1.5;
        }
        
        .service-stats {
          display: flex;
          gap: 8px;
        }
      }
      
      .service-actions {
        margin-bottom: 20px;
        display: flex;
        gap: 10px;
      }
      
      .algorithms-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 16px;
        
        .algorithm-card {
          background: white;
          border-radius: 8px;
          padding: 16px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          border-left: 4px solid #909399;
          transition: all 0.3s ease;
          
          &.running {
            border-left-color: #67c23a;
          }
          
          &.inactive {
            border-left-color: #f56c6c;
          }
          
          &:hover {
            box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
          }
          
          .algorithm-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
            
            .algorithm-title {
              flex: 1;
              
              h5 {
                margin: 0 0 8px 0;
                color: #303133;
                font-size: 16px;
              }
            }
            
            .algorithm-actions {
              display: flex;
              gap: 8px;
              flex-wrap: wrap;
            }
          }
          
          .algorithm-info {
            margin-bottom: 12px;
            
            .algorithm-id {
              font-size: 12px;
              color: #909399;
              margin: 0 0 4px 0;
            }
            
            .algorithm-desc {
              font-size: 14px;
              color: #606266;
              margin: 0;
              line-height: 1.4;
            }
          }
          
          .algorithm-metrics {
            .metrics-grid {
              display: grid;
              grid-template-columns: repeat(3, 1fr);
              gap: 12px;
              
              .metric {
                text-align: center;
                
                .metric-label {
                  display: block;
                  font-size: 12px;
                  color: #909399;
                  margin-bottom: 4px;
                }
                
                .metric-value {
                  display: block;
                  font-size: 14px;
                  font-weight: bold;
                  color: #303133;
                }
              }
            }
          }
        }
      }
    }
  }
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

:deep(.el-alert__content) {
  line-height: 1.6;
}
</style>